import React, { useState , useEffect } from 'react';
import {
  BorderLeftOutlined,
  BorderOuterOutlined
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Breadcrumb, Layout, Menu, theme } from 'antd';
import { MenuListItem } from '../../utils/types';
import { NavLink , Outlet , useNavigate} from "react-router-dom";

const { Header, Content, Footer, Sider } = Layout;

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

function setIcon (type:string) {
  switch(type){
    case "BorderLeftOutlined":
      return <BorderLeftOutlined/>;
    case "BorderOuterOutlined":
      return <BorderOuterOutlined/>

  }
}

function renderMenu(routes:MenuListItem[]) {
    let newMenu:MenuItem[] = [];
    routes?.forEach(item => {
      if(item.menuType){
        newMenu.push(getItem(
            item.menuName,
            item.menuId,
            setIcon(item.menuIcon),
            renderMenu(item.menuChildren as MenuListItem[])
          ))
      }else{
        newMenu.push(getItem(
          <NavLink to={item.menuPath}>{item.menuName}</NavLink>,
          item.menuId,
          setIcon(item.menuIcon),
        ))
      }
    })

    return newMenu;
}


const Home: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [items , setItems] = useState<MenuItem[]>([]);
  const navigate = useNavigate();
  const {
    token: { colorBgContainer },
  } = theme.useToken();

  useEffect(() =>{
    setItems(renderMenu(JSON.parse(localStorage.getItem("routes") as string)));
  },[]);
  const signout = () => {
    const flag = window.confirm("确定退出吗？");
    if(flag){
      //  从本地存储中删除token 和 routes
      //  跳转到登陆页
      localStorage.removeItem("token");
      localStorage.removeItem("routes");
      navigate("/");
    }
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider collapsible collapsed={collapsed} onCollapse={(value) => setCollapsed(value)}>
        <div className="demo-logo-vertical" />
        <Menu theme="dark" defaultSelectedKeys={['1']} mode="inline" items={items} />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }} >
          <button onClick={() => signout()}>退出</button>
        </Header>
        <Content style={{ margin: '0 16px' }}>
          <Breadcrumb style={{ margin: '16px 0' }}>
            <Breadcrumb.Item>User</Breadcrumb.Item>
            <Breadcrumb.Item>Bill</Breadcrumb.Item>
          </Breadcrumb>
          <div style={{ padding: 24, minHeight: 360, background: colorBgContainer }}>
            <Outlet/>
          </div>
        </Content>
        <Footer style={{ textAlign: 'center' }}>Ant Design ©2023 Created by Ant UED</Footer>
      </Layout>
    </Layout>
  );
};

export default Home;